//局部锁现象数据不一致问题
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<unistd.h>
#include<pthread.h>
#include"Mutex.hpp"
using namespace MuteModule;
int ticket = 100;

class ThreadData
{
public:
    ThreadData(std::string n,Mutex& lockp)
    :_name(n),
     _lockp(&lockp)
     {

     }
    std::string _name;
    Mutex* _lockp;
};
/*void* route(void* arg)
{
    ThreadData* td = (ThreadData*) arg;
    while(true)
    {
        td->_lockp->Lock();//加锁
        if(ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket: %d\n",td->_name.c_str(),ticket);
            ticket--;
            td->_lockp->Unlock();//解锁
        }
        else
        {
            td->_lockp->Unlock();//解锁
            break;
        }
    }
    return nullptr;
}*/
void* route(void* arg)
{
    ThreadData* td = (ThreadData*) arg;
    while(true)
    {
        LockGuard (*(td->_lockp));//加锁RAII风格
        if(ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket: %d\n",td->_name.c_str(),ticket);
            ticket--;
        }
        else
        {
            break;
        }
    }
    return nullptr;
}
int main()
{
    Mutex lock;
    pthread_t t1,t2,t3,t4;
    ThreadData* td1 = new ThreadData("thread 1",lock);
    pthread_create(&t1,nullptr,route,td1);

    ThreadData* td2 = new ThreadData("thread 2",lock);
    pthread_create(&t2,nullptr,route,td2);

    ThreadData* td3 = new ThreadData("thread 3",lock);
    pthread_create(&t3,nullptr,route,td3);

    ThreadData* td4 = new ThreadData("thread 4",lock);
    pthread_create(&t4,nullptr,route,td4);
    
    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);
    pthread_join(t4,nullptr);
    return 0;
}